package com.tepth.vehiclemaintenance.mvp.work.content;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.loadmore.LoadMoreView;
import com.google.gson.Gson;
import com.tepth.vehiclemaintenance.R;
import com.tepth.vehiclemaintenance.adapter.WorkItemAdapter;
import com.tepth.vehiclemaintenance.adapter.WorkListAdapter;
import com.tepth.vehiclemaintenance.base.BaseFragment;
import com.tepth.vehiclemaintenance.bean.MaintainDriverRemark;
import com.tepth.vehiclemaintenance.bean.MaintainListWork;
import com.tepth.vehiclemaintenance.bean.VehicleMaintain;
import com.tepth.vehiclemaintenance.bean.request.WorkGuoJianPunchCard;
import com.tepth.vehiclemaintenance.config.SpKey;
import com.tepth.vehiclemaintenance.event.GuoJianPunchCardEvent;
import com.tepth.vehiclemaintenance.event.GuoJianSelectEvent;
import com.tepth.vehiclemaintenance.event.NFCEvent;
import com.tepth.vehiclemaintenance.event.StartBrotherEvent;
import com.tepth.vehiclemaintenance.event.WorkDetailEvent;
import com.tepth.vehiclemaintenance.mvp.work.NFCDialogActivity;
import com.tepth.vehiclemaintenance.mvp.work.detail.DetailFragment;
import com.tepth.vehiclemaintenance.mvp.work.operator.OperatorFragment;
import com.tepth.vehiclemaintenance.tools.AESUtils;
import com.tepth.vehiclemaintenance.tools.SPUtils;
import com.tepth.vehiclemaintenance.tools.ToastUtils;
import com.tepth.vehiclemaintenance.ui.view.LoadingFrameLayout;
import com.tepth.vehiclemaintenance.ui.view.RecyclerViewDecoration;
import com.tepth.vehiclemaintenance.ui.view.dialog.DialogDelegate;
import com.tepth.vehiclemaintenance.ui.view.dialog.SweetAlertDialogDelegate;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by zhangyu on 2017/5/10.
 */

public class ContentFragment extends BaseFragment implements ContentContract.View {
    private static final String PARAMETER = "vehicleMaintain";
    private VehicleMaintain mVehicleMaintain;

    public static ContentFragment newInstance(VehicleMaintain vehicleMaintain) {
        ContentFragment fragment = new ContentFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(PARAMETER, vehicleMaintain);
        fragment.setArguments(bundle);
        return fragment;
    }

    @BindView(R.id.layout_tag_data)
    LoadingFrameLayout mLayoutTagData;
    @BindView(R.id.tag_flow_layout)
    TagFlowLayout mTagLayout;
    @BindView(R.id.swipeLayout_type)
    SwipeRefreshLayout mSwipeLayoutType;
    @BindView(R.id.recycler_view_type)
    RecyclerView mRecyclerViewType;
    @BindView(R.id.recycler_view_item)
    RecyclerView mRecyclerViewItem;
    private ContentContract.Presenter mPresenter;
    private WorkListAdapter mWorkListAdapter;
    private MaintainListWork mCurrentListWork;
    private WorkItemAdapter mWorkItemAdapter;
    private int mOldMaintainListPosition = -1;
    private ArrayList<MaintainDriverRemark> mMaintainDriverRemarks;
    private MaintainListWork.ListContentsBean mListContentsBeanCurrent;
    private int mCurrentContentBeanPosition;
    private GuojianBottomFragment mGuojianBottomFragment;
    private ArrayList<MaintainListWork> doingGuojian = new ArrayList<>();//过检的集合
    private ArrayList<MaintainListWork> undoGuojian = new ArrayList<>();//取消的过检集合
    private List<MaintainListWork.ListContentsBean> doPunchCardList = new ArrayList<>();//待打卡集合
    private List<MaintainListWork.ListContentsBean> canclePunchCardList = new ArrayList<>();//取消打卡集合

    private String name, number;//要提交的作业人的姓名和员工编号
    private String mWorkContentJson;
    private String mWorkConfirmJson, nWorkContentJson;
    private DialogDelegate mDialogDelegate;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mVehicleMaintain = (VehicleMaintain) bundle.getSerializable(PARAMETER);
        }
    }

    @Override
    protected void setPresenter() {
        mPresenter = new ContentPresenter();
        ContentContract.Model model = new ContentModel();
        mPresenter.setVM(this, model);
    }

    @Override
    protected void unbindPresenter() {
        mPresenter.onDestroy();
    }

    @Override
    protected void initView(View view) {
        EventBus.getDefault().register(this);
        //获取司机报修故障
        mLayoutTagData.showLoading();
        //获取作业列表
        mWorkListAdapter = new WorkListAdapter(_mActivity,
                R.layout.item_maintain_work_type, new ArrayList<MaintainListWork>());
        mWorkListAdapter.setEmptyView(R.layout.view_empty, (ViewGroup) mRecyclerViewType.getParent());
        mWorkListAdapter.setLoadMoreView(new LoadMoreView() {
            @Override
            public int getLayoutId() {
                return R.layout.view_load_more;
            }

            @Override
            protected int getLoadingViewId() {
                return R.id.load_more_loading_view;
            }

            @Override
            protected int getLoadFailViewId() {
                return R.id.load_more_load_fail_view;
            }

            @Override
            protected int getLoadEndViewId() {
                return R.id.load_more_load_end_view;
            }
        });
        ((SimpleItemAnimator) mRecyclerViewType.getItemAnimator()).setSupportsChangeAnimations(false);
        mRecyclerViewType.setLayoutManager(new LinearLayoutManager(_mActivity));
        mRecyclerViewType.setAdapter(mWorkListAdapter);
        mRecyclerViewType.addOnItemTouchListener(new OnItemChildClickListener() {

            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                chooseType(position);
            }

        });
        mRecyclerViewType.addItemDecoration(new RecyclerViewDecoration(_mActivity,
                RecyclerViewDecoration.VERTICAL_LIST));
        mSwipeLayoutType.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mSwipeLayoutType.setRefreshing(false);
            }
        });
        mSwipeLayoutType.setRefreshing(true);
        ((SimpleItemAnimator) mRecyclerViewItem.getItemAnimator()).setSupportsChangeAnimations(false);
        mRecyclerViewItem.setLayoutManager(new LinearLayoutManager(_mActivity));
        mRecyclerViewItem.addItemDecoration(new RecyclerViewDecoration(_mActivity,
                RecyclerViewDecoration.VERTICAL_LIST));
        mRecyclerViewItem.addOnItemTouchListener(new OnItemChildClickListener() {

            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_check_state:
                        MaintainListWork.ListContentsBean listContentsBean =
                                mWorkItemAdapter.getItem(position);
                        switch (listContentsBean.getState()) {
                            case 0:
                                listContentsBean.setState(2);
                                changeTypeCount(1);
                                doPunchCardList.add(listContentsBean);
                                break;
                            case 1:
                                listContentsBean.setState(2);
                                changeTypeCount(1);
                                canclePunchCardList.add(listContentsBean);
                                break;
                            case 2:
                                if (listContentsBean.getWorkPersonName() != null) {
                                    listContentsBean.setState(1);
                                    canclePunchCardList.remove(listContentsBean);
                                } else {
                                    listContentsBean.setState(0);
                                    doPunchCardList.remove(listContentsBean);
                                }
                                changeTypeCount(-1);
                                break;
                        }
                        mWorkItemAdapter.notifyItemChanged(position);
                        break;
                    case R.id.layout_content:
                    case R.id.iv_goto:
                        mListContentsBeanCurrent = mWorkItemAdapter.getItem(position);
                        mCurrentContentBeanPosition = position;
                        EventBus.getDefault().post(new StartBrotherEvent(DetailFragment.newInstance
                                (mListContentsBeanCurrent)));
                        break;
                }

            }
        });
        mDialogDelegate = new SweetAlertDialogDelegate(_mActivity);
        requestData();
    }


    private void changeTypeCount(int count) {
        MaintainListWork maintainListWork = mWorkListAdapter.getItem(mOldMaintainListPosition);
        maintainListWork.setTemp_select_number(maintainListWork.getTemp_select_number() + count);
        mWorkListAdapter.notifyItemChanged(mOldMaintainListPosition);
    }

    private void requestData() {
        mPresenter.getDriverRemark();
        mPresenter.getMaintainListWork();
    }

    private void chooseType(int position) {
        if (position == mOldMaintainListPosition) {
            return;
        }
        MaintainListWork temp = mWorkListAdapter.getItem(position);
        temp.setSelected(true);
        if (mCurrentListWork == null) {
            mCurrentListWork = temp;
        } else {
            mCurrentListWork.setSelected(false);
            mWorkListAdapter.notifyItemChanged(mOldMaintainListPosition);
            mCurrentListWork = temp;

        }
        mOldMaintainListPosition = position;
        mWorkListAdapter.notifyItemChanged(mOldMaintainListPosition);

        if (mWorkItemAdapter == null) {
            mWorkItemAdapter = new WorkItemAdapter(_mActivity, R.layout.item_maintain_work_item
                    , temp.getListContents());
            mWorkItemAdapter.setEmptyView(R.layout.view_empty, (ViewGroup) mRecyclerViewType.getParent());
            mWorkItemAdapter.setLoadMoreView(new LoadMoreView() {
                @Override
                public int getLayoutId() {
                    return R.layout.view_load_more;
                }

                @Override
                protected int getLoadingViewId() {
                    return R.id.load_more_loading_view;
                }

                @Override
                protected int getLoadFailViewId() {
                    return R.id.load_more_load_fail_view;
                }

                @Override
                protected int getLoadEndViewId() {
                    return R.id.load_more_load_end_view;
                }
            });
            mRecyclerViewItem.setAdapter(mWorkItemAdapter);
        } else {
            mWorkItemAdapter.setNewData(temp.getListContents());
        }
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_content, container, false);
    }

    @Override
    public void onNetworkError(String msg) {
        mDialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onError(String msg) {
        mDialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onTokenInvalid(String msg) {
        mDialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public String getAuthKey() {
        return SPUtils.getString(_mActivity, SpKey.KEY_AUTH_KEY, "");
    }

    @Override
    public String getWorkContentsJson() {
        ArrayList<MaintainListWork.ListContentsBean> list = new ArrayList<>();
        list.addAll(doPunchCardList);
        list.addAll(canclePunchCardList);
        Gson gson = new Gson();
        return gson.toJson(list);
    }

    @Override
    public String getConfirmJson() {
        return mWorkConfirmJson;
    }

    @Override
    public String getCompleteRemark() {
        return "无";
    }

    @Override
    public int getMaintenanceId() {
        return mVehicleMaintain.getId();
    }

    @Override
    public void showDriverRemarkList(ArrayList<MaintainDriverRemark> list) {
        if (list == null || list.isEmpty()) {
            mLayoutTagData.showEmpty();
        } else {
            mMaintainDriverRemarks = list;
            TagAdapter<MaintainDriverRemark> tagAdapter = new TagAdapter<MaintainDriverRemark>(list) {
                @Override
                public View getView(FlowLayout parent, int position,
                                    MaintainDriverRemark fault) {
                    String remark = fault.getDriverRemark();
                    TextView tv = (TextView) LayoutInflater.from(_mActivity).inflate(R.layout.view_tv,
                            parent, false);
                    if (remark == null || remark.isEmpty()) {
                        tv.setVisibility(View.GONE);
                    } else {
                        tv.setVisibility(View.VISIBLE);
                        tv.setText(remark);
                    }
                    return tv;
                }
            };
            mTagLayout.setAdapter(tagAdapter);
            mLayoutTagData.showContent();
        }
    }

    @Override
    public void showMaintainListWork(ArrayList<MaintainListWork> list) {

        mWorkListAdapter.setNewData(list);
        if (list != null && list.size() > 0) {
            chooseType(0);
        }
        mSwipeLayoutType.setRefreshing(false);
    }

    @OnClick(R.id.view_cover)
    public void onTagLayoutClick() {
        EventBus.getDefault().post(new StartBrotherEvent(OperatorFragment.newInstance
                (mMaintainDriverRemarks)));
    }

    @Override
    public void onLoadTagDataError(String msg) {
        mLayoutTagData.showEmpty();
    }

    @Override
    public void onLoadWorkListDataError(String msg) {
        mSwipeLayoutType.setRefreshing(false);
    }

    @Override
    public void onPunchCardSucceed() {
        ToastUtils.showToast(_mActivity, "打卡成功!");
        mGuojianBottomFragment.dismiss();
        mPresenter.getMaintainListWork();
        doingGuojian.clear();
        undoGuojian.clear();
        mSwipeLayoutType.setRefreshing(true);
    }

    @Subscribe
    public void onWorkDetail(WorkDetailEvent event) {
        List<MaintainListWork.ListContentsBean.ListRemarkBean> listRemark = event.mRemarkList;
        mListContentsBeanCurrent.setListRemark(listRemark);

        if (!event.isReturn) {
            if (mListContentsBeanCurrent.getState() != 2) {
                mListContentsBeanCurrent.setState(2);
                changeTypeCount(1);
            }
            mWorkItemAdapter.notifyItemChanged(mCurrentContentBeanPosition);
        }
    }


    @OnClick(R.id.tv_pass_punch)
    public void onGuoJian() {
        if (mWorkListAdapter.getData() == null || mWorkListAdapter.getData().isEmpty()) {
            ToastUtils.showToast(_mActivity, "数据未加载完成!");
            return;
        }
        mGuojianBottomFragment = GuojianBottomFragment.newInstance(
                (ArrayList<MaintainListWork>) mWorkListAdapter.getData(),
                doingGuojian.size(),
                undoGuojian.size());
        mGuojianBottomFragment.show(getChildFragmentManager(), "guojian_bottom");
    }

    @Subscribe
    public void onGuoJianPunchCardEvent(GuoJianPunchCardEvent event) {
        guojian_bottomListen();
    }

    @Subscribe
    public void onGuojianSelectdEvent(GuoJianSelectEvent event) {
        guojian_list_Listener(event.obj, event.type);
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    private void guojian_list_Listener(MaintainListWork obj, int type) {
        switch (type) {
            case 0:
                doingGuojian.add(obj);
                break;
            case 1:
                doingGuojian.remove(obj);
                break;
            case 2:
                undoGuojian.add(obj);
                break;
            case 3:
                undoGuojian.remove(obj);
                break;
        }
    }

    private int mCurrentRequestCode = 0;

    public void guojian_bottomListen() {
        if (doingGuojian.size() == 0 && undoGuojian.size() == 0)
            return;
        Intent intent = new Intent();
        intent.setClass(_mActivity, NFCDialogActivity.class);
        mCurrentRequestCode = 1003;
        startActivity(intent);
    }

    @Subscribe
    public void onNfcResultEvent(NFCEvent event) {
        String contents = new String(event.msgBuffer);
        update(contents);
    }

    private void update(String contents) {
        String result = "";
        try {
            result = AESUtils.code_desEncrypt(contents);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (result.isEmpty()) {
            ToastUtils.showToast(_mActivity, "保存失败");
            return;
        }
        String[] results = result.split("_");
        if (result.length() < 2) {
            ToastUtils.showToast(_mActivity, "保存失败");
            return;
        }
        number = results[0];
        name = results[1];
        ArrayList<WorkGuoJianPunchCard> list = new ArrayList<>();
        for (MaintainListWork maintainListWork : doingGuojian) {
            list.add(new WorkGuoJianPunchCard(maintainListWork.getContentTypeCode(),
                    1, number, name, maintainListWork.getCompletedRemark()));
        }
        for (MaintainListWork maintainListWork : undoGuojian) {
            list.add(new WorkGuoJianPunchCard(maintainListWork.getContentTypeCode(),
                    1, "", "", maintainListWork.getCompletedRemark()));
        }
        Gson gson = new Gson();
        mWorkConfirmJson = gson.toJson(list);
        mPresenter.punchCard();
        mDialogDelegate.showProgressDialog(true, "正在提交...");
    }
}
